#import "MenuController.h"
#import "TTNeedFullViewController.h"
#import "UserConfigController.h"
#pragma mark DataDources
#import "NeedsViewDataSource.h"
#import "NeedHelpsViewDataSource.h"
#import "FriendsNeedViewDataSource.h"
#import "MyNeedsViewDataSource.h"
#import "AlertsViewDataSource.h"
#pragma mark Models
#import "NeedsModel.h"
#import "NeedsResultsModel.h"
#import "NeedHelpsResultsModel.h"
#import "MyNeedsResultsModel.h"
#import "AlertsModel.h"


#import <QuartzCore/QuartzCore.h>

#import "INDefaultStylesheet.h"

#import "NeedishStore.h"


//static CGFloat kImageWidth = 50;
//static CGFloat kImageHeight = 50;
static const CGFloat kSmallMargin = 6;




@implementation MenuController

@synthesize page = _page, user = _currentUser, need_id;

///////////////////////////////////////////////////////////////////////////////////////////////////
// private

- (NSString*)nameForMenuPage:(MenuPage)page {
  switch (page) {
    case MenuPageMyNeeds:
      return @"My Needs";
    case MenuPageFriendNeeds:
      return @"Friends";
    case MenuPageExploreNeeds:
      return @"Explore";
    case MenuPageAlerts:
      return @"Alerts";
	case MenuPageAbout:
		return @"About";
    default:
      return @"";
  }
}


///////////////////////////////////////////////////////////////////////////////////////////////////
// NSObject

- (id)initWithMenu:(MenuPage)page {
  if (self = [super init]) {
    self.page = page;
	  
	  _activity = [[TTActivityLabel alloc] initWithFrame:CGRectMake(0, 0, 320, 416)
												   style:TTActivityLabelStyleBlackBox
													text:NSLocalizedString(@"Loading...", nil)];	  
  }
  return self;
}

- (id)init {	
  if (self = [super init]) {
    _page = MenuPageNone;	  
	[self.tableView reloadData];
  }
  return self;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Model DataSource

- (void)createModel
{


	NSString *username, *password;
	
	username = [NeedishStore getUserName];
	password = [NeedishStore getPasswordForUsername:username];
	
	if (_page == MenuPageMyNeeds) {	

		if (!username || !password) {
			TTLOG(@"We open userconf");
			[[TTNavigator navigator] openURL:@"in://userconfmodal" animated:NO];
		} else {
			TTLOG(@"We login");		
			NeedishLogin *login = [NeedishLogin loginWithUsername:username andPassword:password];
			login.delegate = self;
			//			self.navigationItem.rightBarButtonItem.enabled = NO;
			[[self view] addSubview:_activity];
			
			if ((!self.dataSource) && (username && password)) { 
				id<TTTableViewDataSource> ds_all = [MyNeedsViewDataSource dataSourceWithItems:nil];
				ds_all.model = CreateMyNeedsModelWithCurrentSettings(@"users", @"my", 20);
				
				self.dataSource = ds_all;
			}			
		}

	}
	else if (_page == MenuPageFriendNeeds) {		
		if ((!self.dataSource) && (username && password)) { 
			id<TTTableViewDataSource> ds_friends = [FriendsNeedViewDataSource dataSourceWithItems:nil];
			ds_friends.model = CreateNeedModelWithCurrentSettings(@"needs", @"friends", 20);
			  
			self.dataSource = ds_friends;
		}
	}
	else if (_page == MenuPageExploreNeeds) {
		if ((!self.dataSource) && (username && password)) { 
			id<TTTableViewDataSource> ds_all = [NeedsViewDataSource dataSourceWithItems:nil];
			ds_all.model = CreateNeedModelWithCurrentSettings(@"needs", @"all", 20);
				  
			self.dataSource = ds_all;
		} 		
	}
	else if (_page == MenuPageAlerts) {
		if ((!self.dataSource)  && (username && password)) { 
			id<TTTableViewDataSource> ds_alerts = [AlertsViewDataSource dataSourceWithItems:nil];
			ds_alerts.model = CreateAlertsModelWithCurrentSettings(@"alerts", @"all", 20);
			
			self.dataSource = ds_alerts;
		}
	}
	else if (_page == MenuPageAbout) {
		if ((!self.dataSource)  && (username && password)) { 
			self.tableViewStyle = UITableViewStyleGrouped;

			self.dataSource = [TTSectionedDataSource dataSourceWithObjects:
							   NSLocalizedString(@"Needish client for iPhone",nil),
							   [TTTableTextItem itemWithText:[NSString stringWithFormat:@"Version: %@", 
															  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]],
							   NSLocalizedString(@"Developed by:", nil),
							   [TTTableTextItem itemWithText:@"Felipe Navarro V." URL:@"in://userView/?user=4106"],
							   
							   NSLocalizedString(@"BETA testers:", nil),
							   [TTTableTextItem itemWithText:@"Daniel X"],
							   nil];
		}
	}
	
	
	
}


///////////////////////////////////////////////////////////////////////////////////////////////////
// TTViewController

- (void)setPage:(MenuPage)page {
  _page = page;
//  _currentUser = [[[User alloc] decodeUser] autorelease];

  self.statusBarStyle = UIStatusBarStyleBlackOpaque;
  self.navigationBarTintColor = TTSTYLEVAR(needishBlueColor);
  self.variableHeightRows = YES;
  self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;	
	
  if (_page == MenuPageMyNeeds) {
	  UIImage* image = [UIImage imageNamed:@"Needs.png"];
	  //self.tabBarItem = [[[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemMostViewed tag:1] autorelease];
	  self.tabBarItem = [[UITabBarItem alloc] initWithTitle:self.title image:image tag:1];
	  
	  self.title = NSLocalizedString(@"My Needs", @"My Needs");
	  self.navigationItem.rightBarButtonItem =
	  [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Logout", nil) style:UIBarButtonItemStyleBordered
									   target:self
									   action:@selector(alertOKCancelAction)] autorelease];	 
	  self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Back" 
																				style:UIBarButtonItemStyleBordered 
																			   target:nil action:nil] autorelease];
  } else if (_page == MenuPageFriendNeeds) {
	  UIImage* image = [UIImage imageNamed:@"Friends.png"];
//	  self.tabBarItem = [[[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemMostViewed tag:0] autorelease];
	  self.tabBarItem = [[UITabBarItem alloc] initWithTitle:self.title image:image tag:1];
	  
	  self.title = NSLocalizedString(@"Friends", @"Friends Title");
	  
  } else if (_page == MenuPageExploreNeeds) {
	  UIImage* image = [UIImage imageNamed:@"Explore.png"];
	  //self.tabBarItem = [[[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemMostViewed tag:1] autorelease];
	  self.tabBarItem = [[UITabBarItem alloc] initWithTitle:self.title image:image tag:2];
	  self.title = NSLocalizedString(@"Explore", @"Explore title");
	  	  
  } else if (_page == MenuPageAlerts) {
	  UIImage* image = [UIImage imageNamed:@"Alerts.png"];
	  //self.tabBarItem = [[[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemMostViewed tag:1] autorelease];
	  self.tabBarItem = [[UITabBarItem alloc] initWithTitle:self.title image:image tag:2];
	  
	  self.title = NSLocalizedString(@"Alerts", @"Need Alerts");

	} else if (_page == MenuPageAbout) {
		UIImage* image = [UIImage imageNamed:@"About.png"];
		//self.tabBarItem = [[[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemMostViewed tag:1] autorelease];
		self.tabBarItem = [[UITabBarItem alloc] initWithTitle:self.title image:image tag:2];
		
		self.title = NSLocalizedString(@"About", @"About");

	}
	
}

- (void)didReceiveMemoryWarning 
{ 
//	[self.dataSource release];
} 


#pragma mark --
#pragma mark Login Stuff




//- (void)viewWillLoad {
////	[[self view] addSubview:_activity];
//	TTLOG(@"We're almost ready");
//}

-(void)loginDidSucceed
{
	TTLOG(@" ====>  We're almost ready");	
	[_activity removeFromSuperview];
	//	self.navigationItem.rightBarButtonItem.enabled = YES;	
}

-(void)loginDidFailWithError:(NSError *)err
{
	UIAlertView *alert;
	[_activity removeFromSuperview];
	//	self.navigationItem.rightBarButtonItem.enabled = YES;
	
	
	if ([[err domain] isEqualToString:@"ineedish"] && [err code] == 1) {
		alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Login failed", nil)
										   message:NSLocalizedString(@"Saved credentials are not valid", nil)
										  delegate:self
								 cancelButtonTitle:NSLocalizedString(@"Ok", nil)
								 otherButtonTitles:NSLocalizedString(@"Settings", nil),nil];
	} else {
		alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Login failed", nil)
										   message:[err localizedDescription]
										  delegate:self
								 cancelButtonTitle:NSLocalizedString(@"Ok", nil)
								 otherButtonTitles:nil];
		
	}
	
	[alert show];
	[alert release];
}


#pragma mark -
#pragma mark - UIAlertViewDelegate

//- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//	// use "buttonIndex" to decide your action
//	//
//	if (buttonIndex == 0)
//	{
//		TTLOG(@"No");
//	}
//	else
//	{
//		TTLOG(@"Yes");
//		[NeedishStore removeAllData];
////		[self.tableView reloadData];
//		//		[[TTNavigator navigator] openURL:@"in://userconf" animated:NO];
//		//		TTOpenURL([NSString stringWithFormat:@"in://userconfmodal"]);		
//		[[TTNavigator navigator] openURL:@"in://userconfmodal" animated:NO];
//	}
//}


- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == 0) {
		/*TODO: make something fancy here later */
		TTLOG(@"No");
	} else {
		[NeedishStore removeAllData];
//		[alertView dismissWithClickedButtonIndex:buttonIndex animated:YES]; 
		[[TTNavigator navigator] openURL:@"in://userconfmodal" animated:YES];
	}
}


///////////////////////////////////////////////////////////////////////////////////////////////////

- (void)alertOKCancelAction
{
	// open a alert with an OK and cancel button
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Logout", nil) message:NSLocalizedString(@"Are you sure you want to logout?", nil)
												   delegate:self cancelButtonTitle:NSLocalizedString(@"No", nil) otherButtonTitles:NSLocalizedString(@"Yes", nil), nil];
	[alert show];
	[alert release];
}


- (void)dealloc {
	[_activity release];
    [super dealloc];
}

@end
 